package com.logistic.server.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.constant.RedisConst;
import com.logistic.server.common.exception.UnauthorizedException;
import com.logistic.server.entity.common.WebUserToken;

import java.util.Objects;

/**
 * 安全服务工具类
 *
 * @author swen
 */
public class SecurityUtils {

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return Objects.requireNonNull(getLoginUser()).getUserId();
        } catch (Exception e) {
            throw new UnauthorizedException("获取用户ID异常" + HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId() {
        try {
            return Objects.requireNonNull(getLoginUser()).getDeptId();
        } catch (Exception e) {
            throw new UnauthorizedException("获取部门ID异常" + HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return Objects.requireNonNull(getLoginUser()).getUserName();
        } catch (Exception e) {
            throw new UnauthorizedException("获取用户账户异常" + HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static WebUserToken getLoginUser() {
        try {
            String token = CookieUtil.get(ServletUtils.getRequest(), Constants.TOKEN);
            if(StrUtil.isNotBlank(token)) {
                return JSONObject.parseObject(SpringUtil.getBean(RedisUtils.class).get(RedisConst.ACCESS_TOKEN + token), WebUserToken.class);
            }
        } catch (Exception e) {
            throw new UnauthorizedException("获取用户信息异常" + HttpStatus.HTTP_UNAUTHORIZED);
        }
        return null;
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String password(String password) {
        return MD5.create().digestHex16(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return StrUtil.equals(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }
}
